import React, { useEffect } from 'react';
import { useHistory, useLocation, useParams } from 'react-router-dom';
import { Spin, message } from 'antd';
import { CmdbContent, CmdbHeader } from '@/components';
import enums from '@/enums';
import AcceptanceStatusBar from './AcceptanceStatusBar';
import AcceptanceForm from './AcceptanceForm';
import { useAcceptanceDetail, useSubmitAcceptanceForm } from './hooks';

/**
 * 验收资料表单
 */
function ResourceAcceptanceForm() {
    const history = useHistory();
    const { search } = useLocation();
    const params = useParams();

    const searchParams = new URLSearchParams(search);
    const id = searchParams.get('id');
    const edit = params.action === 'edit';

    const acceptanceDetail = useAcceptanceDetail();
    const submitAcceptanceForm = useSubmitAcceptanceForm({
        onSuccess() {
            message.success('提交成功');
            history.push('/resource/acceptance');
        },
        onError() {
            message.error('提交失败');
        },
    });

    const renderAcceptanceForm = (props) => {
        return (
            <AcceptanceForm
                edit={edit}
                submitting={submitAcceptanceForm.loading}
                onSubmit={submitAcceptanceForm.run}
                {...props}
            />
        );
    };

    const renderContent = () => {
        if (edit) {
            if (acceptanceDetail.loading) return <Spin />;

            if (acceptanceDetail.data) {
                return (
                    <>
                        <AcceptanceStatusBar data={acceptanceDetail.data} />
                        {renderAcceptanceForm({ initialValues: acceptanceDetail.data })}
                    </>
                );
            }

            return null;
        }

        return renderAcceptanceForm({ initialValues: { cloudArchitecture: 'ComputationStorageSeparation' } });
    };

    useEffect(() => {
        edit && acceptanceDetail.run(id);
    }, []);

    return (
        <CmdbContent>
            <CmdbHeader
                title={`${edit ? '编辑' : '新增'}验收资料`}
                showBackButton
                history={history}
                goBackUrl="/resource/acceptance"
            />
            {renderContent()}
        </CmdbContent>
    );
}

export default ResourceAcceptanceForm;
